<?php

class WSB_Model_Collection implements Iterator, Countable
{
	/**
	 * @var integer
	 */
    protected $_count;

    /**
     * @var array
     */
    protected $_data;

    /**
     * @var string
     */
    protected $_modelClass;

    /**
     * @var WSB_Model_Gateway
     */
    protected $_gateway;

    /**
     * Constructor
     *
     * @param array|object $data
     */
    public function __construct($data)
    {
		if(is_object($data)) {
			$data = (array)$data;
		}
		if(!is_array($data)) {
			throw new Exception('WSB_Model_Collection::__construct(): Initial data must be an array or object');
		}
        $this->_data = $data;
        $this->_count = count($this->_data);
        $this->init();
		if(empty($this->_modelClass)) {
			throw new Exception('WSB_Model_Collection::__construct(): Property \'_modelClass\' must be set.');
		}
    }

    /**
     * @param array $item
     */
    public function add(array $item)
    {
		$this->_data[] = $item;
        $this->_count = count($this->_data);
    }

    /**
     * Initialize object
     *
     * Called from {@link __construct()} as final step of object instantiation.
     *
     * @return void
     */
    public function init()
    {
    }

    /**
     * Set gateway
     *
     * @param WSB_Model_Gateway $gateway
     * @return void
     */
    public function setGateway(WSB_Model_Gateway $gateway)
    {
        $this->_gateway = $gateway;
    }

    /**
     * Get gateway
     *
     * @return WSB_Model_Gateway
     */
    public function getGateway()
    {
        return $this->_gateway;
    }

    /**
     * @return void
     */
    public function reverse()
    {
    	$this->_data = array_reverse($this->_data);
    }

    /**
     * @return integer
     */
    public function count()
    {
        return $this->_count;
    }

    /**
     * @return Zephir_Domain_Model
     */
    public function current()
    {
    	$current = current($this->_data);
    	return new $this->_modelClass($current);
    }

    /**
     * @return integer
     */
    public function key()
    {
        return key($this->_data);
    }

    /**
     * @return array
     */
    public function next()
    {
        return next($this->_data);
    }

    /**
     * @return array
     */
    public function rewind()
    {
        return reset($this->_data);
    }

    /**
     * @return boolean
     */
    public function valid()
    {
    	return array_key_exists($this->key(), $this->_data);
    }

	/**
	 * @return array
	 */
	public function toArray()
	{
		return $this->_data;
	}

	/**
	 * @todo
	 * @return string
	 */
	public function toJson()
	{
	}

	/**
	 * @todo
	 * @return string
	 */
	public function toXml()
	{
	}

}